package servlet.control;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.VForumTitle;
import model.VUser;
import Persistant.Dao.ForumDAO;
import Persistant.Dao.UserDAO;
import Persistent.imple.ForumDAOImpl;
import Persistent.imple.UserDAOImpl;

public class BlogerServlet extends HttpServlet {

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String userid = request.getParameter("bloger");
		UserDAO udao = new UserDAOImpl();
		VUser blogeruser = udao.getVUserById(userid);
		
		ForumDAO fdao = new ForumDAOImpl();
		
		int articleAmount = fdao.getTForumAmountByUser(userid);
		
		
		
		int pageAmount = fdao.getPageAmount(userid,4);
		int curpage = 1;
		String scupage = request.getParameter("curpage");
		if(scupage!=null){
		try{
			curpage = Integer.parseInt(scupage);
			}catch(Exception e){
				curpage = 1 ;
			}
			if(curpage <=0)
				curpage = 1;
			else if(curpage > pageAmount)
				curpage = pageAmount;
		}
		
		List<VForumTitle> list = fdao.getForumListByPage(userid, curpage, 4);
		
		request.setAttribute("blogeruserid", userid);
		request.setAttribute("blogeruser", blogeruser);
		request.setAttribute("articleAmount", articleAmount);
		request.setAttribute("pageAmount", pageAmount);
		request.setAttribute("curpage", curpage);
		request.setAttribute("forumlist", list);
		RequestDispatcher rd = request.getRequestDispatcher("bloger.jsp");
		rd.forward(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

}
